package cn.datawin.bms.modules.provider.service.impl;

import cn.datawin.bms.modules.provider.mapper.ProvProviderMapper;
import cn.datawin.bms.modules.provider.mapper.ProvProviderParamMapper;
import cn.datawin.bms.modules.provider.service.ProvProviderChannelService;
import cn.datawin.bms.modules.provider.service.ProvProviderParamService;
import cn.datawin.bms.modules.provider.service.ProvProviderService;
import cn.datawin.bms.provider.bo.ProvProviderBo;
import cn.datawin.bms.provider.entity.ProvApiProgramEntity;
import cn.datawin.bms.provider.entity.ProvProviderChannelEntity;
import cn.datawin.bms.provider.entity.ProvProviderEntity;
import cn.datawin.bms.provider.entity.ProvProviderParamEntity;
import cn.datawin.bms.provider.redis.ProvProviderRedisDto;
import cn.datawin.common.core.util.RedisUtils;
import cn.datawin.constant.RedisPattern;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.datawin.constant.RedisPattern.CSTM_PROVIDER_START;

/**
 * 上游供应商
 *
 * @author datawin-sms
 * @date 2025-08-20 15:16:04
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class ProvProviderServiceImpl extends ServiceImpl<ProvProviderMapper, ProvProviderEntity> implements ProvProviderService {

	private final ProvProviderParamService provProviderParamService;

	private final ProvProviderChannelService provProviderChannelService;

    @Override
    public ProvProviderEntity newProvProvider() {
		if(!RedisUtils.hasKey(CSTM_PROVIDER_START)){
			RedisUtils.incr(CSTM_PROVIDER_START, 500000L);
		}
		long account = RedisUtils.incr(CSTM_PROVIDER_START,1L);
		ProvProviderEntity provProvider = new ProvProviderEntity();
		provProvider.setCode(account+"");
		provProvider.setStatus(1);

		return provProvider;
    }

	@Override
	public boolean saveProvider(ProvProviderBo provProvider) {
		log.info("saveProvider:{}", JSON.toJSONString(provProvider));
		//插入ProvProvider记录
		ProvProviderEntity provProviderEntity = new ProvProviderEntity();
		BeanUtil.copyProperties(provProvider,provProviderEntity);
		boolean save = this.save(provProviderEntity);
		if(save){
			//插入ProvProviderProgram记录,遍历templateFields，每一个kv为一条记录
			List<ProvProviderParamEntity> provProviderParamEntities = new ArrayList<>();
			Map<String, String> templateFields = provProvider.getTemplateFields();
			for (Map.Entry<String, String> entry : templateFields.entrySet()) {
				ProvProviderParamEntity provProviderParamEntity = new ProvProviderParamEntity();
				provProviderParamEntity.setProviderId(provProviderEntity.getId());
				String key = StrUtil.trim(entry.getKey());
				String value = StrUtil.trim(entry.getValue());
				if(StrUtil.isNotBlank(key)&&StrUtil.isNotBlank(value)){
					provProviderParamEntity.setFieldName(entry.getKey());
					provProviderParamEntity.setFieldValue(entry.getValue());
					provProviderParamEntities.add(provProviderParamEntity);
				}


			}
			if(CollUtil.isNotEmpty(provProviderParamEntities)) {
				provProviderParamService.saveBatch(provProviderParamEntities);
			}
			dataToCache(provProviderEntity.getId());
		}



		return save;
	}

	/**
	 * 刷新providerRedis缓存
	 * @param id
	 */
	private void dataToCache(Long id) {

		ProvProviderEntity provProvider = baseMapper.selectById(id);

		ProvProviderRedisDto provProviderRedisDto = new ProvProviderRedisDto();
		provProviderRedisDto.setId(provProvider.getId());
		provProviderRedisDto.setName(provProvider.getName());
		provProviderRedisDto.setApiProgramId(provProvider.getApiProgramId());

		Map<String, String> params = provProviderParamService.getParams(id);
		provProviderRedisDto.setParams(params);
		provProviderRedisDto.setStatus(provProvider.getStatus());
		String rKey = String.format(RedisPattern.PROV_PROVIDER_CACHE,id);
		RedisUtils.set(rKey,provProviderRedisDto);
		//测试查询
		ProvProviderRedisDto provProviderRedisDto1 = RedisUtils.get(rKey);
		log.info("provProviderRedisDto1:{}", JSON.toJSONString(provProviderRedisDto1));
	}

	@Override
	public ProvProviderBo getProviderById(Long id) {
		//查询ProvProvider数据
		ProvProviderEntity provProviderEntity = this.getById(id);
		if(provProviderEntity==null) return null;
		ProvProviderBo provProviderBo = new ProvProviderBo();
		BeanUtil.copyProperties(provProviderEntity,provProviderBo);
		//查询ProvProviderParam数据
		List<ProvProviderParamEntity> provProviderParamEntities = provProviderParamService.lambdaQuery()
				.eq(ProvProviderParamEntity::getProviderId, id)
				.list();
		if(CollUtil.isNotEmpty(provProviderParamEntities)){
			Map<String,String> templateFields = new HashMap<>();
			for (ProvProviderParamEntity provProviderParamEntity : provProviderParamEntities) {
				templateFields.put(provProviderParamEntity.getFieldName(),provProviderParamEntity.getFieldValue());
			}
			provProviderBo.setTemplateFields(templateFields);
		}

		return provProviderBo;
	}

	@Override
	public boolean updateProviderByBo(ProvProviderBo provProvider) {
		log.info("saveProvider:{}", JSON.toJSONString(provProvider));
		//插入ProvProvider记录
		ProvProviderEntity provProviderEntity = new ProvProviderEntity();
		BeanUtil.copyProperties(provProvider,provProviderEntity);
		this.updateById(provProviderEntity);
		//删除原始的记录
		provProviderParamService.remove(new LambdaQueryWrapper<ProvProviderParamEntity>().eq(ProvProviderParamEntity::getProviderId,provProviderEntity.getId()));
		//插入ProvProviderProgram记录,遍历templateFields，每一个kv为一条记录
		List<ProvProviderParamEntity> provProviderParamEntities = new ArrayList<>();
		Map<String, String> templateFields = provProvider.getTemplateFields();
		for (Map.Entry<String, String> entry : templateFields.entrySet()) {
			ProvProviderParamEntity provProviderParamEntity = new ProvProviderParamEntity();
			provProviderParamEntity.setProviderId(provProviderEntity.getId());
			String key = StrUtil.trim(entry.getKey());
			String value = StrUtil.trim(entry.getValue());
			if(StrUtil.isNotBlank(key)&&StrUtil.isNotBlank(value)){
				provProviderParamEntity.setFieldName(entry.getKey());
				provProviderParamEntity.setFieldValue(entry.getValue());
				provProviderParamEntities.add(provProviderParamEntity);
			}


		}
		if(CollUtil.isEmpty(provProviderParamEntities)) return false;

		boolean b = provProviderParamService.saveBatch(provProviderParamEntities);

		if (b){
			//刷新绑定的providerChannel的redis缓存
			//查询所有的providerChannel
			List<ProvProviderChannelEntity> provProviderChannelEntities = provProviderChannelService.lambdaQuery()
					.eq(ProvProviderChannelEntity::getProviderId, provProviderEntity.getId())
					.list();
			if(CollUtil.isNotEmpty(provProviderChannelEntities)){

				for (ProvProviderChannelEntity provProviderChannelEntity : provProviderChannelEntities) {
					//刷新缓存
					provProviderChannelService.dataToCache(provProviderChannelEntity.getId());
				}

			}
		}

		dataToCache(provProviderEntity.getId());

		return b;


	}
}
